<template>
  <div>
    <el-card shadow="never">
      <template slot="header">
        <span>客户资金流水</span>
      </template>

      <!-- 搜索区域 -->
      <Search :search-options="searchOptions" @search="handleSearch">
        <template #customSelectSlot="{ form }">
          <el-select v-model="form.tradeType" placeholder="请选择交易类型" style="width: 180px" clearable>
            <el-option v-for="item in tradeTypeOptions" :key="item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </template>
        <template #customStatusSlot="{ form }">
          <div style="margin-top: 14px;">
            <el-radio-group v-model="form.tradeStatus" @change="handleStatusChange"
                            class="status-tag-group">
              <el-radio :label="null" class="status-tag status-tag-all">全部</el-radio>
              <el-radio v-for="item in tradeStatusOptions" :key="item.value" :label="item.value"
                        class="status-tag">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </div>
        </template>
      </Search>

      <!-- 表格区域 -->
      <el-table v-loading="listLoading" element-loading-text="数据正在加载中" :data="data" border fit
                highlight-current-row style="width: 100%">
        <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
                         :align="item.align" :width="item.width">
          <template slot-scope="{ row, $index }">
            <div v-if="item.slot === 'index'">{{ $index + 1 }}</div>
            <div v-else-if="item.prop === 'tradeType'">
              {{ tradeTypeMap[row.tradeType] || '--' }}
            </div>
            <div v-else-if="item.prop === 'tradeStatus'">
              <el-tag :type="getStatusTagType(row.tradeStatus)">
                {{ tradeStatusMap[row.tradeStatus] || '--' }}
              </el-tag>
            </div>
            <div v-else-if="item.prop === 'amount'">
              <span style="color: #E6A23C; font-weight: bold;">{{ formatPrice(row.amount) }}</span>
            </div>
            <div v-else-if="item.prop === 'materialType'">
              {{ materialTypeMap[row.materialType] || '--' }}
            </div>
            <div v-else-if="item.prop === 'price' && row.materialType">
              {{ formatPrice(row.price) }}
            </div>
            <div v-else-if="item.prop === 'weight' && row.materialType">
              {{ formatWeight(row.weight) }}g
            </div>
            <div v-else>{{ row[item.prop] || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="text" size="mini" @click="viewDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <Pagination :page="current" :page_size="size" :total="total" @sizeChange="sizeChange"
                  @currentChange="pageChange"/>
    </el-card>
  </div>
</template>

<script>
import Search from '@/components/Search.vue';
import Pagination from '@/components/Pagination.vue';
import { getCustomerFundList } from '@/views/property/api/customer';
import { IMG_URL } from '@/utils/utils';

export default {
  name: 'CustomerFundList',
  components: {
    Search,
    Pagination
  },
  props: {
    customerId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      fileList: [],
      IMG_URL,
      listLoading: false,
      searchOptions: [

        {
          label: "物料类型",
          key: "materialType",
          type: "input",
          placeholder: "请输入物料类型",
          value: null,
        },
        {
          label: "交易类型",
          key: "tradeType",
          type: "slot",
          slotName: "customSelectSlot",
          value: null,
        },
        {
          label: "交易时间",
          key: "tradeTime",
          type: "daterange",
          startKey: "startTime",
          endKey: "endTime",
          placeholder: "请选择交易时间范围",
          value: [],
        },
        {
          label: "交易状态",
          key: "tradeStatus",
          type: "slot",
          slotName: "customStatusSlot",
          value: null,
        },
      ],
      columns: [
        {
          label: "序号",
          prop: "index",
          type: "index",
          slot: "index",
          align: "center",
          width: 60,
        },
        {
          label: "数量/重量(g)",
          prop: "weight",
          align: "center",
          width: 120,
        },
        {
          label: "交易金额(元)",
          prop: "amount",
          align: "center",
          width: 130,
        },
        {
          label: "物料类型",
          prop: "materialType",
          align: "center",
          width: 120,
        },
        {
          label: "交易单价(元/g)",
          prop: "price",
          align: "center",
          width: 130,
        },
        {
          label: "交易类型",
          prop: "tradeType",
          align: "center",
          width: 120,
        },
        {
          label: "交易状态",
          prop: "tradeStatus",
          align: "center",
          width: 120,
        },
        {
          label: "交易时间",
          prop: "tradeTime",
          align: "center",
          width: 180,
        },
      ],
      current: 1,
      size: 20,
      data: [],
      total: 0,
      searchParams: {},
      // 物料类型选项
      materialTypeOptions: [
        {value: 'GOLD', label: '黄金'},
        {value: 'SILVER', label: '白银'},
        {value: 'PLATINUM', label: '铂金'},
        {value: 'PALLADIUM', label: '钯金'},
      ],
      // 物料类型映射
      materialTypeMap: {
        'GOLD': '黄金',
        'SILVER': '白银',
        'PLATINUM': '铂金',
        'PALLADIUM': '钯金',
      },
      // 交易类型选项
      tradeTypeOptions: [
        {value: 'RECHARGE', label: '入款'},
        {value: 'ENCASH', label: '回款'},
        {value: 'BUY', label: '买料'},
        {value: 'SELL', label: '卖料'},
        {value: 'SAVE', label: '入料'},
        {value: 'TAKE', label: '回料'},
        {value: 'REFUND', label: '违约结算'},
        {value: 'ADD_RETAINER', label: '追加定金'},
      ],
      // 交易状态选项
      tradeStatusOptions: [
        {value: 'INIT', label: '申请中'},
        {value: 'AUDITING', label: '审核中'},
        {value: 'AUDIT_PASS', label: '通过'},
        {value: 'CANCEL', label: '不通过'},
      ],
      // 交易类型映射
      tradeTypeMap: {
        'RECHARGE': '入款',
        'ENCASH': '回款',
        'BUY': '买料',
        'SELL': '卖料',
        'SAVE': '入料',
        'TAKE': '回料',
        'REFUND': '违约结算',
        'ADD_RETAINER': '追加定金',
      },
      // 交易状态映射
      tradeStatusMap: {
        'INIT': '申请中',
        'AUDITING': '审核中',
        'AUDIT_PASS': '通过',
        'CANCEL': '不通过',
      },
    }
  },
  watch: {
    customerId: {
      handler(newVal) {
        console.log("cusId:",this.customerId,"|",newVal);
        if (newVal) {
          this.current = 1;
          this.init();
        }
      },
      immediate: true
    }
  },
  methods: {
    // 格式化价格
    formatPrice(price) {
      if (price === null || price === undefined || price === '') return '0.00'
      const num = Number(price)
      if (!isFinite(num)) return '0.00'
      return num.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },
    // 重量 千分符
    formatWeight(weight) {
      if (weight === null || weight === undefined || weight === '') return '0'
      const num = Number(weight)
      if (!isFinite(num)) return '0'
      return num.toLocaleString('zh-CN')
    },
    // 初始化数据
    init() {
      // 只有当customerId存在时才获取数据
      if (!this.customerId) {
        this.data = [];
        this.total = 0;
        return;
      }

      
      const {current, size, searchParams} = this;
      const p = {current, size, ...searchParams, cusId: this.customerId}
      this.listLoading = true;

      getCustomerFundList(p).then(res => {
        this.listLoading = false;
        this.total = res.total || 0;
        this.data = res.records || [];
      }).catch(() => {
        this.listLoading = false;
        this.$message.error('获取数据失败');
      })
    },
    // 处理搜索
    handleSearch(params) {
      this.searchParams = params;
      this.current = 1;
      this.init();
    },
    // 处理交易状态变化
    handleStatusChange(value) {
      // 当选择"全部"时，清空状态值
      if (value === '') {
        this.searchParams.tradeStatus = null;
      } else {
        this.searchParams.tradeStatus = value;
      }
      // 重新搜索
      this.current = 1;
      this.init();
    },
    // 页码改变
    pageChange(page) {
      this.current = page;
      this.init();
    },
    // 每页条数改变
    sizeChange(size) {
      this.size = size;
      this.current = 1;
      this.init();
    },
    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        'AUDITING': 'warning',
        'AUDIT_PASS': 'success',
        'CANCEL': 'danger',
      };
      return typeMap[status] || 'info';
    },
    // 查看详情
    viewDetail(row) {
      this.$router.push(`/customer/fund/detail/${row.id}`)
    },
    // 提供给父组件调用的搜索方法
    handleSearchFromParent() {
      this.current = 1;
      this.init();
    }
  }
}
</script>

<style scoped lang="scss">
.search-container {
  margin-bottom: 20px;
}
</style>